package com.example.demo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.entity.UserBean;
import org.springframework.util.DigestUtils;

import java.util.Calendar;

public class JwtUtil {
    //加密secret
    private static final String SECRET = "EDU-ONLINE";
    //过期时间
    private static final Integer TIME_OUT_DAY = 30;
    //需要重新生成的天数 如果token的时间超过这个 则重新生成token
    private static final Integer NEED_CREATE_DAY = 7;
    /**
     * 生成token
     * @param user
     * @return
     */
    public static String createToken(UserBean user){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,TIME_OUT_DAY);
        String token = JWT.create()
                .withClaim("userId", user.getId())
//                .withClaim("key",
//                        DigestUtils.md5DigestAsHex(user.getPassword().getBytes()))
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }
    /**
     * 获取token信息 如果token有误则返回null
     * @param token
     * @return
     */
    public static DecodedJWT getTokenInfo(String token){
        try {
            return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        }catch (Exception e){
            return null;
        }
    }
    /**
     * 获取用户ID
     * @param decodedJWT




    解耦整合springboot拦截器
    1、创建拦截器
     * @return
     */
    public static Integer getUserId(DecodedJWT decodedJWT){
        return decodedJWT.getClaim("userId").asInt();
    }
}